import json
import os
from config import PROJECT_ROOT

def get_json_path(traget_dirctory,traget_filename):
    return os.path.join(PROJECT_ROOT, traget_dirctory, traget_filename)

def get_json_element(json_file,target_desc,select_keys = None):
    """
    提取json文件中的方法
    :param json_file:指定的json文件路径
    :param traget_desc: 要提取对象的desc值
    :param select_keys: 要提取的键列表
    :return:
    """
    result_dict = {}
    try:
        with open(json_file,'r',encoding='utf-8') as f:
            data = json.load(f)
        #找到目标desc
        traget_obj = next((item for item in data if item.get('desc')==target_desc), None)
        if not traget_obj:
            print(f"未找到desc为'{target_desc}'的对象")
            return result_dict
        for key,value in traget_obj.items():
            if key == 'desc':
                continue
            if select_keys and key in select_keys:
                result_dict[key] = value
            else:
                result_dict[key] = value
        return result_dict

    except FileNotFoundError:
        print(f"错误，文件'{json_file}'不存在")
    except json.decoder.JSONDecodeError:
        print(f"错误，文件'{json_file}'不是有效的格式")
    except Exception as e:
        print(f"提取数据时出错：{str(e)}")

    return result_dict